<!--
 * @Description: 登录页面
 * @Author: oscar
 * @Date: 2021-12-03 15:00:07
-->
<template>
  <el-row>
    <el-col :span="24">
      <div class="login-box">
        <h1>Weixin Admin System v1</h1>
        <div class="login-wrap">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="120px"
            class="login-form"
          >
            <el-form-item label="UserName" prop="username">
              <el-input
                v-model="ruleForm.username"
                type="text"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="Password" prop="pass">
              <el-input
                v-model="ruleForm.pass"
                type="password"
                autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script lang="ts">
import { login } from '@/api/account'
import { ElMessage } from "element-plus";
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Please input the password"));
      } else {
        callback();
      }
    };
    const validateUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Please input the UserName"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        pass: "",
        username: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        username: [{ validator: validateUserName, trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = {
            username: this.ruleForm.username,
            password: this.ruleForm.pass
          }
          login(param).then( res => {
            if(res.token) {
              ElMessage.success("登录成功")
              localStorage.setItem('token', res.token)
              this.$router.push('/home')
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="less">
.login-box{
  width: 600px;
  margin: 20px auto;
}
h1{
  padding-top: 20%;
}
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
h1 {
  text-align: center;
}
.login-wrap {
  display: flex;
  justify-content: center;
  width: 100%;
}
.login-form {
  width: 500px;
  margin: 0 auto;
}
</style>
